Rails中redirect_to的post_url(@post)该怎么用?

redirect_to的帮助举了一个例子:

redirect_to post_url(@post), :status=> :found, :notice => "Pay attention to the road"

其中的post_url(@post)是什么意思呢?网上没搜到具体的例子,能否举一个实际例子?

2个回答

http://guides.rubyonrails.org/routing.html#paths-and-urls

_path _url这样的方法都是链接生成辅助方法

比如你在路由定义了 resources :photos
那么会有这些_path _url方法

[quote]photos_path returns /photos
new_photo_path returns /photos/new
edit_photo_path(:id) returns /photos/:id/edit (for instance, edit_photo_path(10) returns /photos/10/edit)
photo_path(:id) returns /photos/:id (for instance, photo_path(10) returns /photos/10)[/quote]

post_url(@post)也是一个方法,最终返回http://host/posts/1 (这里的1是@post的id)

认真看看官方的手册,英文有压力的话,就看

bbsforum
bbsforum 懂了,感谢
接近 8 年之前 回复

这是rails2.3.11的官方地址http://guides.rubyonrails.org/v2.3.11/routing.html

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
为什么rails2.1中的link_to无效

[code="java"]<% for department in @departments %> <tr> <td><%=h department.Name %></td> <td><%=h department.Number %></td> <td><%=h department.ParentID %></td> <td><%=h department.Note %></td> <td><%= link_to 'Show', department_path(department.ID) %></td> <td><%= link_to 'Edit', edit_department_path(department.ID) %></td> <td><%= link_to 'Destroy',department_path(department.ID), :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %>[/code] 这样的delete不起作用 [code="java"]<% for department in @departments %> <tr> <td><%=h department.Name %></td> <td><%=h department.Number %></td> <td><%=h department.ParentID %></td> <td><%=h department.Note %></td> <td><%= link_to 'Show', department %></td> <td><%= link_to 'Edit', edit_department_path(department) %></td> <td><%= link_to 'Destroy',department, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %>[/code] 这样三个都不行! 问:上面的代码行吗? 是不是rails2.1方式有变 或者数据库字段不行! rails2.1 RESTful routes 哪里有资料 [b]问题补充:[/b] map.resources :departments 已经设置! 就是http提交后没有处理就返回! [b]问题补充:[/b] class DepartmentsController < ApplicationController # GET /departments # GET /departments.xml def index @departments = Department.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @departments } end end # GET /departments/1 # GET /departments/1.xml def show @department = Department.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @department } end end # GET /departments/new # GET /departments/new.xml def new @department = Department.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @department } end end # GET /departments/1/edit def edit @department = Department.find(params[:id]) end # POST /departments # POST /departments.xml def create @department = Department.new(params[:department]) respond_to do |format| if @department.save flash[:notice] = 'Department was successfully created.' format.html { redirect_to(@department) } format.xml { render :xml => @department, :status => :created, :location => @department } else format.html { render :action => "new" } format.xml { render :xml => @department.errors, :status => :unprocessable_entity } end end end # PUT /departments/1 # PUT /departments/1.xml def update @department = Department.find(params[:id]) respond_to do |format| if @department.update_attributes(params[:department]) flash[:notice] = 'Department was successfully updated.' format.html { redirect_to(@department) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @department.errors, :status => :unprocessable_entity } end end end # DELETE /departments/1 # DELETE /departments/1.xml def destroy @department = Department.find(params[:id]) @department.destroy respond_to do |format| format.html { redirect_to(departments_url) } format.xml { head :ok } end end end [b]问题补充:[/b] 上面是controller 本人刚学 谢谢热心的回答!受益匪浅 [b]问题补充:[/b] 代码是用Scaffolding 生成的

Rails 3 form_for Ajax调用

<div class="post-text" itemprop="text"> <p>I have method in my controller:</p> <pre><code>def work_here @company = Company.find(params[:id]) current_user.work_apply(current_user, @company) redirect_to company_path end </code></pre> <p>On my view:</p> <pre><code>&lt;%= render 'companies/work_form' if signed_in? %&gt; </code></pre> <p>_work_form.html.erb:</p> <pre><code>&lt;%= form_for company, :remote =&gt; true, :url =&gt; { :controller =&gt; "companies", :action =&gt; "work_here" } do |f| %&gt; &lt;%= f.hidden_field :id, :value =&gt; company.id %&gt; &lt;%= f.submit "I working here" %&gt; </code></pre> <p>&lt;% end %&gt;</p> <p>And I have a work_here.js.erb file:</p> <pre><code>$("#work_at_form").html("&lt;%= escape_javascript("render('companies/works')") %&gt;") </code></pre> <p>But my form works without ajax request(in other pages ajax forks fine), my js.erb file never use. Can anyone give me advise? Thanks.</p> </div>

ubuntu rails环境搭建

http://www.iteye.com/wiki/rails_deployment/1296-deploy-rails-on-linux 安装robin大概顺序安装了rails开发环境。 安装 ImageMagick 和 RMagic (可选)没装,其他全部安装。 问题:用lighty调用rails时,rails时用rails带的脚手架创建的posts,能访问,但是在新建post页面提交时,报错,log如下: [code="ruby"] /!\ FAILSAFE /!\ 2009-09-04 21:01:46 +0800 Status: 500 Internal Server Error closed stream /usr/local/ruby/lib/ruby/gems/1.9.1/gems/rack-1.0.0/lib/rack/rewindable_input.rb:84:in `make_rewindable' /usr/local/ruby/lib/ruby/gems/1.9.1/gems/rack-1.0.0/lib/rack/rewindable_input.rb:26:in `read' /usr/local/ruby/lib/ruby/gems/1.9.1/gems/rack-1.0.0/lib/rack/request.rb:142:in `POST' /usr/local/ruby/lib/ruby/gems/1.9.1/gems/rack-1.0.0/lib/rack/methodoverride.rb:15:in `call' /usr/local/ruby/lib/ruby/gems/1.9.1/gems/actionpack-2.3.3/lib/action_controller/params_parser.rb:15:in `call' /usr/local/ruby/lib/ruby/gems/1.9.1/gems/actionpack-2.3.3/lib/action_controller/session/cookie_store.rb:93:in `call' /usr/local/ruby/lib/ruby/gems/1.9.1/gems/actionpack-2.3.3/lib/action_controller/reloader.rb:29:in `call' ...... [/code] 同样的rails应用直接用script/server启动就没有任何错误。是哪的问题呢? [b]问题补充:[/b] script/server启动后,没有任何问题,查看posts,插入post,修改post都正常,只要用lighty调用fcgi,post查看页面可以浏览,但是不能新建。 [b]问题补充:[/b] 脚手架自己生成的代码: [code="ruby"] # POST /posts # POST /posts.xml def create @post = Post.new(params[:post]) respond_to do |format| if @post.save flash[:notice] = 'Post was successfully created.' format.html { redirect_to(@post) } format.xml { render :xml => @post, :status => :created, :location => @post } else format.html { render :action => "new" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end[/code] [b]问题补充:[/b] 环境: rails 2.3.4 ruby 1.9.1 注:lighty里面rails version=“development”,这样才能看到上面的log日志,用生产环境没有上述日志,我能肯定不是数据库的问题。每次只要post就会出错,现在正在看rack是什么东西,是不是这个影响了。 [b]问题补充:[/b] 问题解决: 卸载所有ruby相关的东西包括gem装的所有东西,重新安装ruby1.8.7,然后按照robin的步骤安装rails,正常。

update_attributes更新失败~!~!

update_attributes更新一定要所有的属性都写上吗?怎么写部分的属性不能更新成功呢? 页面部分,如果点了修改密码的checkbox会把新密码的两个文本框显示出来,让用户输入新的密码..否则是不能输入的.. [code="html"] <% form_tag :action => "update",:id => @user do %> <table width="100%" border="0" cellpadding="1" cellspacing="1" class="date_table"> <tr> <td colspan=2><%= error_messages_for 'user' %></td> </tr> <tr> <td width="70">名字:</td> <td><%= @user.name %></td> </tr> <tr> <td>旧密码:</td> <td> <%=password_field :user, :old_password, :size => 15 %> <%=check_box_tag :change_password, "true",false,:onclick => "changePassowrd(this)" %>修改密码 <script>$('change_password').checked = false;</script> </td> </tr> <tr style="display:none;" id="txtPwd1"> <td>密码:</td> <td><%=password_field :user, :password, :size => 15 %></td> </tr> <tr style="display:none;" id="txtPwd2"> <td>确认密码:</td> <td><%=password_field :user, :password_confirmation, :size => 15 %></td> </tr> <tr> <td>权限:</td> <td><%= select(:user, :level , @types) %></td> </tr> <tr> <td colspan="2"> <%= submit_tag "修改用户信息" %> <%= return_page "返回" , :type => "button" %> </td> </tr> </table> <%end %> [/code] 在Controller上判断是否需要修改密码,如果不需要修改密码会把参数里边的两个密码删除,不然密码就为空了... 然后更新,没有任何异常的执行成功,但是没有更新成功~! 如果将 params[:user].delete("password_confirmation") params[:user].delete("password") 替换成 params[:user][:password_confirmation] = params[:user][:old_password] params[:user][:password] = params[:user][:old_password] 就能正常更新成功! 这是为什么? [code="ruby"] def update @user = User.find params[:id] if request.post? #如果修改密码,而且新密码为空,提示错误,否则将新密码设置和旧密码一样 if params[:change_password] and params[:user][:password].empty? flash[:notice] = "必须输入新密码" redirect_to :action => :update else params[:user].delete("password_confirmation") params[:user].delete("password") end #如果旧密码为空,提示信息 if params[:user][:old_password].empty? flash[:notice] = "必须输入旧密码" redirect_to :action => :update #如果旧密码相同,进行修改 elsif User.authenticate @user.name,params[:user][:old_password] params[:user].delete("old_password") @user.update_attributes(params[:user]) flash[:notice] = "修改成功"; redirect_to :action => :index else flash[:notice] = "旧密码错误" end end end [/code]

不渲染Rails AJAX

<div class="post-text" itemprop="text"> <p>I want to render partial "shared/_feed.html.erb" in my "static_pages/index.html.erb" view after adding a new post but it just dissappers "#posts"! I don't know, where to find my mistake! Here is the result: </p> <pre><code>Started POST "/posts" for 127.0.0.1 at 2017-05-10 10:50:23 +0300 Processing by PostsController#create as JS Parameters: {"utf8"=&gt;"✓", "authenticity_token"=&gt;"uTjOINWDjrTfzvkNowDH9vKRTGrHenps88DZdnZmifM=", "post"=&gt;{"title"=&gt;"fasdfsdf", "body"=&gt;"sdfasfa"}, "commit"=&gt;"Post"} User Load (1.4ms) SELECT `users`.* FROM `users` WHERE `users`.`active` = 1 AND `users`.`id` = 1 LIMIT 1 (0.7ms) BEGIN SQL (382.8ms) INSERT INTO `posts` (`body`, `created_at`, `published_at`, `title`, `updated_at`, `user_id`) VALUES ('sdfasfa', '2017-05-10 07:50:23', NULL, 'fasdfsdf', '2017-05-10 07:50:23', 1) User Load (1.5ms) SELECT `users`.* FROM `users` WHERE `users`.`active` = 1 AND `users`.`id` = 1 LIMIT 1 SQL (32.0ms) UPDATE `users` SET `posts_count` = COALESCE(`posts_count`, 0) + 1 WHERE `users`.`active` = 1 AND `users`.`id` = 1 (51.1ms) COMMIT Rendered posts/_post_added.html.erb (0.2ms) (2.2ms) SELECT COUNT(*) FROM `posts` WHERE `posts`.`user_id` = 1 Rendered shared/_feed.html.erb (0.0ms) Rendered posts/create.js.erb (11.4ms) Completed 200 OK in 503.6ms (Views: 16.8ms | ActiveRecord: 471.7ms) </code></pre> <p><a href="https://i.stack.imgur.com/TuZWS.jpg" rel="nofollow noreferrer">"static_pages/index.html.erb"</a></p> <p>views/posts/create.js.erb:</p> <pre><code> $("#add_post").replaceWith("&lt;%= j render(:partial =&gt; 'posts/post_added') %&gt;"); $(".posts_count").html("&lt;%= pluralize(current_user.posts.count, 'post') %&gt;"); $("#posts").replaceWith("&lt;%= j render(:partial =&gt; 'shared/feed', collection: @feed_items) %&gt;") </code></pre> <p>routes:</p> <pre><code>Courses::Application.routes.draw do resources :users do collection { post :import} end resources :users do resources :posts end root to: "static_pages#index" get "/home" =&gt; "static_pages#index" resources :sessions, only: [:new, :create, :destroy] match 'index', to: 'static_pages#index', via: [:get, :post] match '/signup', to: 'users#new' match '/signin', to: 'sessions#new' match '/signout', :to =&gt; 'sessions#destroy' resources :posts resources :books do post 'search', on: :collection end end </code></pre> <p>views/static_pages/index.erb.html:</p> <pre><code>&lt;% if signed_in? %&gt; &lt;div class="row"&gt; . . &lt;aside class="col-md-4"&gt; &lt;section&gt; &lt;%= render 'shared/user_info' %&gt; &lt;/section&gt; &lt;section class="add_post" id="add_post"&gt; &lt;h3&gt;Post Add&lt;/h3&gt; &lt;%= render 'shared/post_form' %&gt; &lt;/section&gt; &lt;/aside&gt; &lt;div class="col-md-8"&gt; &lt;h3&gt;Post Feed&lt;/h3&gt; &lt;div id="posts"&gt; &lt;%= render 'shared/feed' %&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;% else %&gt; &lt;div class="center hero-unit"&gt; &lt;h1&gt;Welcome to the Sample App&lt;/h1&gt; &lt;h2&gt; This is the home page for the &lt;a href="http://railstutorial.org/"&gt;Ruby on Rails Tutorial&lt;/a&gt; sample application. &lt;/h2&gt; &lt;%= link_to "Sign up now!", signup_path, class: "btn btn-large btn-primary" %&gt; &lt;%= link_to image_tag("rails.png", alt: "Rails"), 'http://rubyonrails.org/' %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>posts_controller.rb</p> <pre><code>class PostsController &lt; ApplicationController before_filter :authorize, only: [:edit, :destroy, :update] before_filter :correct_user, only: [:edit, :update, :destroy] def new @post = Post.new end def create @post = current_user.posts.build(params[:post]) respond_to do |format| if @post.save flash[:success] = "Post created!" format.html { redirect_to @post } format.js format.json { render json: @post, status: :created, location: @post } else flash.now[:error] = "your message" @feed_items = [] render 'static_pages/home' end end end def index @posts = Post.order(:created_at).paginate(page: params[:page]) @post = current_user.posts.build if signed_in? end def post_params params.require(:post).permit(:title,:body) end def show if signed_in? @post = current_user.posts.build @feed_items = current_user.feed.paginate(page: params[:page]) end end def edit @post = Post.find(params[:id]) end def destroy @post.destroy # redirect_to root_path, :notice =&gt; 'The Post has been deleted!' respond_to do |format| format.html { redirect_to posts_url } format.js { render :layout =&gt; false } format.json { head :no_content } end end def update @post = Post.find(params[:id]) if @post.update_attributes(params[:post]) redirect_to posts_path, :notice =&gt; 'The Post is Updated' else render "edit" end end private def correct_user @post = current_user.posts.find_by_id(params[:id]) redirect_to root_url, :notice =&gt; 'Can\'t' if @post.nil? end end </code></pre> <p>static_pages_controller.rb </p> <p>class StaticPagesController &lt; ApplicationController</p> <pre><code> def index if signed_in? @post = current_user.posts.build @feed_items = current_user.feed.paginate(page: params[:page]) end end def destroy end def create end def show end end </code></pre> <p>views/shared/_feed.html.erb</p> <pre><code>&lt;% if @feed_items.any? %&gt; &lt;ol class="posts"&gt; &lt;%= render partial: 'shared/feed_item', collection: @feed_items %&gt; &lt;/ol&gt; &lt;%= will_paginate @feed_items %&gt; &lt;% end %&gt; </code></pre> <p>views/shared/_feed_item.html.erb</p> <pre><code>&lt;li id="&lt;%= feed_item.id %&gt;"&gt; &lt;%= link_to gravatar_for(feed_item.user), feed_item.user %&gt; &lt;span class="user"&gt; &lt;%= link_to feed_item.user.username, feed_item.user %&gt; &lt;/span&gt;&lt;br&gt; &lt;span class="content"&gt;&lt;u&gt;&lt;%= feed_item.title %&gt;&lt;/u&gt;&lt;/span&gt;&lt;br&gt; &lt;span class="content"&gt;&lt;%= feed_item.body %&gt;&lt;/span&gt;&lt;br&gt; &lt;span class="timestamp"&gt;&lt;small&gt; Posted &lt;%= time_ago_in_words(feed_item.created_at) %&gt; ago. &lt;/small&gt;&lt;/span&gt; &lt;% if current_user?(feed_item.user) %&gt; &lt;%= link_to "delete", feed_item, method: :delete, data: { confirm: "You sure?" }, title: feed_item.title, remote: true, :class =&gt; 'delete_post' %&gt; &lt;% end %&gt; &lt;hr&gt; &lt;/li&gt; </code></pre> <p>and here is my git <a href="https://github.com/mkiselyow/hw5_hw6/commit/eec43a2c6faabde4fc75c4146ca41ced534ce999" rel="nofollow noreferrer">https://github.com/mkiselyow/hw5_hw6/commit/eec43a2c6faabde4fc75c4146ca41ced534ce999</a></p> </div>

如何应用权限管理系统到实际中?

我自己做了一个基于角色控件的权限管理系统 表结构: [quote]users: id,name,password roles_users: roles_id,users_id roles: id,name permissions_roles: permissions_id,roles_id permissions: id,name,action[/quote] 大家一看就应该明白这几张表是什么关系了吧?一个用户可以拥有多个角色,一个角色也可以拥有多个用户,一个角色可以拥有多个操作权限,而一个操作权限也可以属于多个角色. 另外要说的一点就是:在表permissions中,name表示操作的名字,就是用来显示在页面上的,如"删除新闻",而action是就代表真正的操作. 现在对于user,role,permission的操作我都实现了(包括对usser对role的勾选和role对permission的勾选) 而且在我的User模型中,我也写了方法,用以取得user所拥有的权限: [code="ruby"] class User < ActiveRecord::Base has_and_belongs_to_many :roles #User login validate def self.login_validate(name, password) user = User.find_by_name(name) if user if user.password == password return user else user = nil end end user end #Get user's all permissions def permissions user_permissions = Array.new for role in self.roles user_permissions += role.permissions end user_permissions end end[/code] 现在说说对于这个系统,我的思想.我的权限主要是用于后台管理方面的(/admin),因此在/app/controllers/admin下有 [code="ruby"] class Admin::AdminController < ActionController::Base #Set layout for Admin board layout "admin" before_filter :authorizate def authorizate puts "authorizate" is_login? #这里现在写什么啊?大家给指点一下啊 end #Validate the user has loged in or not def is_login? unless session[:user] flash[:notice] = "Please login first!" redirect_to "/login" end end end[/code] 对于admin模块下的其它controller,都是继承这个Admin Controller,我现在就是迷惑了,不知道如何验证权限. 我以前用Java做权限管理系统(SSH),大体思想是这样的:所用的操作最终都是基于URL请求的,eg:http://localhost:8080/admin/postAction.do?method=list(postAction代表了一个模块,而list代表了一个操作) 我在用户登录是就把用户的权限操作列表保存到Session中,然后写一个作用于/admin的过滤器,用来检查当前登录用户的权限列表中的许可的url是否包含请求的url,这样就能实现权限的管理. 然而现在在rails中,url不适用了,大家给指点一下,如何基于我目前所做的来应用这个权限验证. 问题补充: 难道我还要在/admin模块下的每一个controller中的action方法中加入判断当前登录的用户是否拥有权限? 如在Admin:ostController中 def index #if session[:user].permissions has "post_index" ? if not,redirect to 'you have no permission to do this!!' page end 哇,要是这样我累死了!! 希望大家不要给的是与这样类似的答案,说简单是一点就是,我想尽量让我的权限管理与业务无关,也就是说移植性要好!!! [b]问题补充:[/b] 谢谢xxj,我现在的Admin::PostController是这样的 [code] class Admin::PostsController < Admin::AdminController before_filter :authorize, :only => [:index, :show, :new, :edit, :destroy] def authorize logger.debug self.controller_name << "/" << self.action_name logger.debug "-------------------------#{self.action_name}" logger.debug session[:user].permission_urls[3] p session[:user].permission_urls[3] == (self.controller_name << "/" << self.action_name) unless session[:user].permission_urls.include?( self.controller_name + "/" + self.action_name ) flash[:notice] = "You have not permission to do it!" redirect_to :controller => "admin/welcome" end end [/code] 我的permission_urls中明明存在"posts/index",为什么我请求/admin/posts/始终跳到没有权限的提示页面呢?我用pust输入作了二者的比较,明明相等,却还是输出false

Ruby on Rails重定向并将数据发送到PHP脚本

<div class="post-text" itemprop="text"> <p>I have a script on Ruby on Rails. It has to redirect to a PHP script in a different server. But I also need this PHP script to receive some data from Rails, preferably hidden somewhere (as raw data, or as a post). </p> <p>Then the PHP will receive that data and do something with it (I actually want to start a session for the current user on the PHP server).</p> <p>How can I acheieve this? Or something close to this?</p> <hr> <p>I need something very similar to what happens when I submit an HTML form via POST. I need it to send data via POST AND to redirect to the given URL.</p> <p>When I do</p> <pre><code>Net::HTTP.post_form(URI.parse(URL), {k: 'somek', u: someu, p: somep, e: somee}) </code></pre> <p>It stays where it is.</p> </div>

Rails 3和Ajax的困惑

<div class="post-text" itemprop="text"> <p>In short, I don't understand ajax with rails. I did this <a href="http://tekn0t.net/ajax-example-with-rails-3-and-jquery" rel="nofollow">tutorial</a> a little while ago and I can get it to work. No problems. The problems seem arise when I have more than one model. </p> <p>For example, if I have a model "cats", I use the tutorial to implement some ajax, works nicely - each time I add a new cat to the list, it appears at the top without reloading the page. Then I add a "dogs" model, and I render the _dog.html.erb file in the cats index and call on it with something like @dogs.each do |dog| etc. </p> <p>Now I need to implement the ajax for the dogs, but do I put the ajax files into create.js.erb in the dogs folder or in the cats create.js.html folder? I've tried both, no success. The first model, in this example cats, will continue to work, but the others don't. I know that its half working because the page doesn't reload when I hit enter, but nothing is generated either. I've checked the id's, all correct.</p> <p>Is there anything else I should be looking for? My logic says that if i'm in the cats index and rendering something from _dog.html.erb, I should put all the create ajax in the cats create.js.html folder…. </p> <p>Help is more than appreciated.</p> <p>Also, just as a small second question, I read another <a href="http://keithschacht.com/getting-ajax-to-work-in-rails-3-with-jquery/" rel="nofollow">tutorial</a> and it advised me to delete everything in the public/javascripts folder except "application.js", which in my case is blank. I haven't because ajax is working, just not for the other models. Should I take the tutorials advise?</p> <p>Thanks again.</p> <p>Update</p> <p>This is the code from "show" in the cats controller.</p> <pre><code>@dog = Dog.new respond_to do |format| format.html end </code></pre> <p>Update 2</p> <p>Ok, so "Cats" is really "Games", and "Dogs" is really "Features". I used the cats and dogs examples because I thought in theory it would be easier, sorry if it made it more confusing :).</p> <p>The code - the ajax for creating games in the games index is working, but the ajax for creating features in the games show is not. The games show is where I want to create new features using ajax. the features are created but only viewable after a page reload.</p> <pre><code> class GamesController &lt; ApplicationController def index @games = Game.paginate(:page =&gt; params[:page], :per_page =&gt; 10) @game = Game.new respond_to do |format| format.html end end def show @user = User.find(params[:id]) @gameid = Game.find(params[:id]) @features = Feature.paginate(:page =&gt; params[:page], :per_page =&gt; 8, :conditions =&gt; {:game_id =&gt; @gameid}) @feature = Feature.new respond_to do |format| format.html end end def create @game = Game.new(params[:game]) respond_to do |format| if @game.save format.html { redirect_to(games_url, :notice =&gt; 'game was successfully created.') } format.js else format.html { redirect_to(games_url) } end end end def destroy @game = Game.find(params[:id]) @game.destroy respond_to do |format| format.html { redirect_to(games_url) } format.js end end end class FeaturesController &lt; ApplicationController def index @features = Feature.all @feature = Feature.new respond_to do |format| format.html end end def show end def create @feature = Feature.new(params[:feature]) respond_to do |format| if @feature.save format.html { redirect_to(features_url, :notice =&gt; 'feature was successfully created.') } format.js else format.html { redirect_to(features_url) } end end end def destroy @feature = Feature.find(params[:id]) @feature.destroy respond_to do |format| format.html { redirect_to(features_url) } format.js end end end (features/create.js.erb) $('#features').prepend('&lt;%= escape_javascript(render(@feature)) %&gt;'); $('#features &gt; li:first').effect('highlight', {}, 3000); $('#features_form &gt; form')[0].reset(); (games/create.js.erb) $('#games').prepend('&lt;%= escape_javascript(render(@game)) %&gt;'); $('#games &gt; li:first').effect('highlight', {}, 3000); $('#game_form &gt; form')[0].reset(); (games/index) &lt;h1&gt;Games&lt;/h1&gt; &lt;table&gt; &lt;tr&gt; &lt;td class="main"&gt; &lt;ul id="games"&gt; &lt;% @games.each do |game| %&gt; &lt;%= render 'game', :game =&gt; game %&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;% if signed_in? %&gt; &lt;div id="game_form"&gt; &lt;%= render 'form' %&gt; &lt;/div&gt; &lt;% else %&gt; &lt;% end %&gt; &lt;/td&gt; &lt;td class="sidebar"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; (games/show) &lt;h1&gt;Features&lt;/h1&gt; &lt;table&gt; &lt;tr&gt; &lt;td class="main"&gt; &lt;h2&gt;Features&lt;/h2&gt; &lt;div id="features_form"&gt; &lt;%= render 'features/form' %&gt; &lt;/div&gt; &lt;ul id="features" style="margin:0;padding:0;"&gt; &lt;% @features.each do |feature| %&gt; &lt;%= render 'features/feature', :feature =&gt; feature %&gt; &lt;% end %&gt; &lt;%= will_paginate @features, :class =&gt; 'pagination' %&gt; &lt;/ul&gt; &lt;/td&gt; &lt;td class="sidebar"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> </div>

Rails和Jquery Ajax

<div class="post-text" itemprop="text"> <p><br> I follow this <a href="http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/" rel="nofollow">tutorial</a> (except I put gem 'jquery-rails' in my gemfile ). </p> <p>The problem, if I click to new post, and fill the form and click to create -&gt; ajax don't work, and show method showing the simple post.</p> <p>my create.js.erb:</p> <pre><code>$('body').html("&lt;h1&gt;&lt;%= escape_javascript(@post.title) %&gt;&lt;/h1&gt;").append("&lt;%= escape_javascript(@post.content) %&gt;"); </code></pre> <p>create method</p> <pre><code>def create @post = Post.new(params[:post]) respond_to do |format| if @post.save format.html { redirect_to(@post, :notice =&gt; 'asdasd') } format.js else format.html { render :action =&gt; "new" } format.js end end </code></pre> <p>end</p> <p>_form.html.erb</p> <pre><code> &lt;%= form_for(@post, :remote =&gt; true) do |f| %&gt; &lt;% if @post.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;h2&gt;&lt;%= pluralize(@post.errors.count, "error") %&gt; prohibited this post from being saved:&lt;/h2&gt; &lt;ul&gt; &lt;% @post.errors.full_messages.each do |msg| %&gt; &lt;li&gt;&lt;%= msg %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;div class="field"&gt; &lt;%= f.label :name %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;%= f.label :title %&gt;&lt;br /&gt; &lt;%= f.text_field :title %&gt; &lt;/div&gt; &lt;div class="field"&gt; &lt;%= f.label :content %&gt;&lt;br /&gt; &lt;%= f.text_area :content %&gt; &lt;/div&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> </div>

Rails 3.0.x AJAX问题

<div class="post-text" itemprop="text"> <p>This is probably a very simple question to answer. i am new to Rails and am having difficulty figuring out something that I am certain is trivial. I have a simple link_to "Show" which is remote and works great. However once i click a remote link and the content is displayed into/from my partial I cannot seem to update that content by clicking again on another link. My server logs are showing the correct calls being made so I believe there must be something wrong I am doing with the callback. Maybe this has something to do with my :locals assignment in my partial. to better understand here is my code...</p> <p>application.js</p> <pre><code>$(function() { $("#showreqs a").live("click", function() { $.getScript(this.href); return false; }); }); </code></pre> <p>_showreq.html.erb (very simple to prove concept)</p> <pre><code>&lt;%= @project.name %&gt; </code></pre> <p>show.js.erb</p> <pre><code>$("#showreq").replaceWith("&lt;%= escape_javascript(render :partial =&gt; 'showreq', :locals =&gt; { :project =&gt; @project}) %&gt;") </code></pre> <p>projects.html.erb (only section that matters)</p> <pre><code>&lt;div id="showreqs"&gt; &lt;%= form_for(@project) do |f| %&gt; &lt;%= render 'shared/error_messages' %&gt; &lt;p&gt; Name: &lt;%= f.text_field :name %&gt; Owner: &lt;%= f.select :user_id, options_from_collection_for_select(@users, 'id', 'name'), :class =&gt; 'genForm_dropBox' %&gt; &lt;%= f.submit "Create Project" %&gt; &lt;/p&gt; &lt;% end %&gt; &lt;ol&gt; &lt;% @projects.each do |t| %&gt; &lt;li&gt; &lt;%= t.name %&gt; - Owner: &lt;%= t.user.name %&gt; - &lt;%= link_to "Show", t, :action =&gt; "show", :remote =&gt; true %&gt; | &lt;%= link_to "delete", t, :method =&gt; :delete, :confirm =&gt; "You sure?", :title =&gt; "Delete" %&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ol&gt; &lt;/div&gt; </code></pre> <p>projectscontroller (very ugly and will clean)</p> <pre><code>class ProjectsController &lt; ApplicationController def index @title = "Requirements" @users = User.order("created_at").all @project = Project.new @projects = Project.all end def show @users = User.order("created_at").all @project = Project.find(params[:id]) @projects = Project.all end def create @project = Project.new(params[:project]) if (defined?(@project_e)).nil? @project_e = Project.new(params[:project]) end if @project.save flash[:success] = "Successfully created a Project." redirect_to projects_path else flash[:error] = "You made some errors" redirect_to projects_path end end def update @project = Project.find(params[:id]) if @user.update_attributes(params[:user]) flash[:success] = "Project updated." redirect_to projects_path else flash[:error] = "You made some errors" redirect_to projects_path end end def destroy Project.find(params[:id]).destroy flash[:success] = "Project destroyed." redirect_to projects_path end end </code></pre> <p>If you need any other code such as routes let me know but i assumed my routes and everything else is fine since this does works when "show" link is first clicked.</p> </div>

Rails Ajax更新div

<div class="post-text" itemprop="text"> <p>Hi i'm new to rails and i want to move a user story in its correct column depending on its state (to be done, in progress,..) with ajax my show template contains four divs with classed (ToBeDone, InProgress, ToBeVerified, Completed)</p> <p>my update.js.erb</p> <pre><code>$("div.&lt;%= @user_story.state.underscore %&gt;:first").append("&lt;%= j render(@user_story)%&gt;"); </code></pre> <p>and my update action</p> <pre><code> if !@user_story.users.include? current_user @user_story.users &lt;&lt; current_user end format.html { redirect_to @user_story.project, notice: 'User story was successfully updated.' } format.json { render :show, status: :ok, location: @user_story } format.js </code></pre> <p>and my user_story partial (this form is submitted when the user selects state)</p> <pre><code>&lt;%= form_for [@project, user_story], remote: true do |f|%&gt; &lt;div class="field" id='my_select_chzn'&gt; &lt;%= f.label :state %&gt; &lt;%= f.select :state, ['To be done', 'In progress', 'To be verified', 'Completed'], {:selected =&gt; user_story.state }, :id =&gt;'select-state', :class =&gt; 'chosen-select'%&gt; &lt;/div&gt; &lt;%end%&gt; </code></pre> <p>Please help, thanks and sorry for this long post.</p> </div>

Rails,AJAX表单验证

<div class="post-text" itemprop="text"> <p>I am new to jQuery, AJAX, and javascript in general, and I am trying to do some front end validation for a rails form that uses an ajax call to have the server run a query. It seems to work well, if I am in the debugger (since the AJAX call has enough time to return and stop the submission of the form), but it wont work all of the time when I am just testing it without the debugger. I believe this happens because after the ajax call, the javascript validation method exits, and the form submits. Here is my javascript method</p> <pre><code> $('#runner-job-submit').click(function(e) { runnerJobValidation(e); }); function runnerJobValidation(e) { var user_login = $('#user_login').val(); var name = $('#name').val(); var location = $('#location').val(); var description = $('#description').val(); var user_exists; //AJAX call to check if user exists in the database $.post("/jobs/user_exists", {user_login: user_login}, function (response) { if(response == "false") { $('#runner-new-job-errors').html(''); e.preventDefault(); $('#runner-new-job-errors').append('&lt;small style="color:red"&gt; User doesnt exist &lt;/small&gt;'); } }); if(user_login == "" || name == "" || location == "" || description == "") { $('#runner-new-job-errors').html(''); e.preventDefault(); $('#runner-new-job-errors').append('&lt;small style="color:red"&gt; Please fill out all fields &lt;/small&gt;'); } } </code></pre> <p>And here is my controller action url it is hitting</p> <pre><code> def user_exists? user_login = params[:user_login] user = User.where("login = ?", user_login).first user_exists = user.present? respond_to do |format| format.js { render :json =&gt; user_exists.to_json} format.html { redirect_to jobs_path } end end </code></pre> <p>Can someone please tell me the correct way to do this. I feel the solution is to somehow prevent <code>runnerJobValidation()</code> from exiting before <code>response</code> is received from the server, but I just dont know how to do this.</p> </div>

AJAX渲染局部

<div class="post-text" itemprop="text"> <p>I am trying to accomplish what I think to be the most direct, though certainly not the most elegant, replication of a reddit style vote button. I have code that works without the AJAX, but I would like users to be able to click the vote buttons and they change appropriately without reloading the page (Hence the AJAX).</p> <p>The problem occurs when I try to remove the vote button clicked on and replace with the appropriate 'highlighted' vote button. The reason I am replaceing the vote button is because I need to change it to a button that will unvote if clicked on. </p> <p>(I have simplified this to just handle just upvoting since downvoting is the same mexhanic). Here is my <strong>view</strong>:</p> <pre><code> &lt;% @posts.each do |post| %&gt; &lt;%= post.content %&gt; &lt;% if current_user.voted_as_when_voted_for post %&gt; &lt;%= render 'upvoted', post: post %&gt; &lt;% else %&gt; &lt;%= render 'upvote', post: post %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>The voted_as_when_voted_for method returns true if they have upvoted the post. Here is the upvote and upvoted <strong>forms</strong>:</p> <pre><code>&lt;%= link_to image_tag('upvoted.png', size: '18'), remove_like_post_path(post), method: :put, remote: true, id: "upvoted#{post.id}" %&gt; &lt;%= link_to image_tag('upvote.png', size: '18'), like_post_path(post), method: :put, remote: true, id: "upvote#{post.id}" %&gt; </code></pre> <p><strong>Here is my controller:</strong></p> <pre><code>def upvote @post = Post.find(params[:id]) @post.liked_by current_user respond_to do |format| format.html { redirect_to @post.parent } format.js {} end end def remove_upvote @post = Post.find(params[:id]) @post.unliked_by current_user respond_to do |format| format.html { redirect_to @post.parent } format.js {} end end </code></pre> <p><strong>upvote.js.erb:</strong> and <strong>upvoted.js.erb:</strong></p> <pre><code>$('#upvote&lt;%= @post.id %&gt;').remove().append('&lt;%= j render("upvoted") %&gt;'); $('#upvoted&lt;%= @post.id %&gt;').remove().append('&lt;%= j render("upvote") %&gt;'); </code></pre> <p>With those files I get the following console errors:</p> <pre><code>PUT http://localhost:3000/posts/96/like 500 (Internal Server Error) NameError in Posts#upvote undefined local variable or method `post' for #&lt;#&lt;Class:0x007fde1836cbf0&gt;:0x007fde18c00af0&gt; </code></pre> <p><strong>_upvote.html.erb</strong> and <strong>_upvoted.html.erb</strong></p> <pre><code>&lt;%= link_to image_tag('upvote.png', size: '18'), like_post_path(post), method: :put, remote: true, id: "upvote#{post.id}" %&gt; &lt;%= link_to image_tag('upvoted.png', size: '18'), like_post_path(post), method: :put, remote: true, id: "upvoted#{post.id}" %&gt; </code></pre> <p>I also tried something like this based on the link below:</p> <pre><code>$('#upvote&lt;%= @post.id %&gt;').remove().after('&lt;%= j render "upvoted", post: @post %&gt;'); </code></pre> <p>When I use that code, the upvote is succesfully removed, but the upvoted form is not added on. So it seems that I need to use the instance variable, but something is still not quite working.</p> <p>What am I missing??</p> <p>This person seemed to have a similar problem: <a href="https://stackoverflow.com/questions/11654021/rails-ajax-render-partial-voting-system">Rails Ajax Render Partial</a></p> </div>

Rails的简单ajax请求

<div class="post-text" itemprop="text"> <p>i have a problem with ajax request:</p> <p>in my app i am trying to configure a simple rank system, and i set it up, but whan i click on rank button - i reload the page and rank is refreshed.</p> <p>Help my realize that in ajax: </p> <p>i done that:</p> <p>in <code>posts/show.html.erb</code> i have that:</p> <pre><code> &lt;div id='vote_update'&gt; &lt;%= render 'vote/update' %&gt; &lt;/div&gt; </code></pre> <p>in <code>vote/_update.html.erb</code> i have :</p> <pre><code>&lt;% if can? :update, Vote %&gt; &lt;%= form_for([@post, @post.vote], remote: true) do |f| %&gt; ... &lt;%= f.submit "vote" %&gt; </code></pre> <p>in <code>vote/update.js.erb</code> i have:</p> <pre><code>$('#vote_update').html("&lt;%= j render('vote/update') %&gt;"); </code></pre> <p>and in vote_controller.rb i have:</p> <pre><code> def update post = Post.find(params[:post_id]) vote = post.vote ... respond_to do |format| if vote.save format.html { redirect_to post_path(post), :notice =&gt; "You vote counted!" } format.js end end end </code></pre> <p>if i remove romete: true - everything goes right ( page is reload, i saw (:notice) "You vote counted!" and rating is updated, but if i put remote: true back, i saw nothing ( some mistakes in firebug console ) - but when i reload page - ratign is updated, nd i saw norml result - i think i madesome mistakes in redirecting or i dont know</p> <p>help please</p> </div>

Rails Ajax无法重新加载

<div class="post-text" itemprop="text"> <p>Creating real time chat app, but whenever I post a message I have to reload the page to see my new message. The chat does not reload by itself.</p> <h3>_form.html.erb</h3> <pre><code>&lt;div class="well"&gt; &lt;%= form_for @comment, remote: true do |f| %&gt; &lt;div class="form-group"&gt; &lt;%= f.label :body, 'Enter your comment:' %&gt; &lt;%= f.text_area :body, rows: 3, class: 'form-control', required: true, maxlength: 2000 %&gt; &lt;small class="label label-warning"&gt;Cannot be blank or contain more than 2000 symbols.&lt;/small&gt; &lt;/div&gt; &lt;%= f.submit 'Post', class: 'btn btn-primary btn-lg' %&gt; &lt;% end %&gt; &lt;/div&gt; </code></pre> <h3>_comments.html.erb</h3> <pre><code>&lt;li class="media comment"&gt; &lt;%= link_to image_tag(comment.user.avatar_url, alt: comment.user.name, class: "media-object"), comment.user.profile_url, target: '_blank', class: 'pull-left' %&gt; &lt;div class="media-body"&gt; &lt;h4 class="media-heading"&gt;&lt;%= link_to comment.user.name, comment.user.profile_url, target: '_blank' %&gt; says &lt;small class="text-muted"&gt;[at &lt;%= comment.created_at.strftime('%-d %B %Y, %H:%M:%S') %&gt;]&lt;/small&gt;&lt;/h4&gt; &lt;p&gt;&lt;%= comment.body %&gt;&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <h3>create.js.erb</h3> <pre><code>publisher = client.publish('/comments', { message: '&lt;%= j render @comment %&gt;' }); publisher.callback(function() { $('#comment_body').val(''); $('#new_comment').find("input[type='submit']").val('Submit').prop('disabled', false) }); publisher.errback(function() { alert('There was an error while posting your comment.'); }); </code></pre> <p><a href="https://github.com/bodrovis/SitepointMiniChat" rel="nofollow">git source</a></p> <h3>Edit: added comments_controller.rb</h3> <pre><code>class CommentsController &lt; ApplicationController def new @comment = Comment.new @comments = Comment.order('created_at DESC') end def create respond_to do |format| if current_user @comment = current_user.comments.build(comment_params) if @comment.save flash.now[:success] = 'Your comment was successfully posted!' else flash.now[:error] = 'Your comment cannot be saved.' end format.html {redirect_to root_url} format.js else format.html {redirect_to root_url} format.js {render nothing: true} end end end private def comment_params params.require(:comment).permit(:body) end end </code></pre> </div>

Ruby on Rails实时更新

<div class="post-text" itemprop="text"> <p>Okay, what i am looking for is a way to get an ajax script to run in the background of a page and look to see if there is a new record in the database and if there has grab that record and display that on my page.</p> <p>i also do not want to use plugins i would rather do this myself as i prefer to learn how to do it and easier to make changes if i need it for something different in the future</p> <p>im quite new to ajax and ruby on rails so a bit of explaining may be in order</p> <p>This is my controller currently when i a user updates the content it changes without the page refreshing but what i want is it to also get new data</p> <pre><code> class NotificationsController &lt; ApplicationController # GET /notifications # GET /notifications.json def index @notifications = Notification.all end def show end def update @notification = Notification.find(params[:id]) @notification.update_attributes(:content =&gt; params[:content][:content]) respond_to do |format| format.html { redirect_to notifications_path } format.json { render json: @notification} end end end </code></pre> <p>This is the js file</p> <pre><code>$(document).ready(function(){ $('input[type=submit]').on('click', function(event){ var form = $(this).parent('form'); event.preventDefault(); $.ajax({ type:"POST", url: form.attr('action'), data: form.serialize(), success: function(data){ console.log('this worked') $('#'+ data.id).html(data.content) }, error: function(data){ console.log('failed') }, dataType: 'JSON' }); }); }); </code></pre> <p>and this is my html file</p> <pre><code>&lt;% content_for :titleheader do %&gt; NOTIFICATIONS &lt;% end %&gt; &lt;h1&gt;Listing Notifications&lt;/h1&gt; &lt;% @notifications.each do |notification| %&gt; &lt;%= form_for notification do |f| %&gt; &lt;%= notification.id %&gt; &lt;div id="&lt;%= notification.id %&gt;"&gt;&lt;%=notification.content %&gt;&lt;/div&gt; &lt;%= notification.read %&gt; &lt;%= text_field "content", "content" %&gt; &lt;%= f.submit "change status" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>As you can tell i have not made a create action yet because im not sure if i am going to have to do this through ajax or something</p> <p>help is very appreciated</p> </div>

Turbolinks 5 ajax开机自检

<div class="post-text" itemprop="text"> <p>In my Rails 5 / Turbolinks 5 application i would like to put the html resulting from a form submission into a div.</p> <p>The form is a</p> <pre><code>= form_for(user) do |f| </code></pre> <p>standard rails form.</p> <p>After a successful submission a redirect is send to the browser</p> <pre><code>respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was created.' } </code></pre> <p>when i submit the form via ajax:</p> <pre><code>$(".dialog").on("submit", "form", function(e){ e.preventDefault(); $.ajax({ url: $(this).attr("action"), method: "POST", data: $(this).serialize() }).done(function(data) { $(".dialog .canvas").html(data); }); }); </code></pre> <p>the from gets submitted and the server's redirect_to statement redirects the browser the the new user's page.</p> <p>The redirect causes turbolinks to replace the body with the content of the page the browser was redirected to. instead i want to replace a specific div $(".dialog .canvas").html(data). how can i prevent this behaviour of turbolinks. </p> </div>

路由ajax rails麻烦

<div class="post-text" itemprop="text"> <p>I have such jquery code:</p> <pre><code> $(".quantity").blur(function() { console.log("upd"); $.ajax({ url: "/line_items/update_quantity/", type: "GET", data: {id: $(this).attr('id'), quantity: $(this).attr('quantity'), cart: $(this).attr('cart')} }); }); </code></pre> <p>But this code generate me such url:</p> <blockquote> <p>.../line_items/update_quantity/?id=29&amp;quantity=111&amp;cart=27</p> </blockquote> <p>But i need such url:</p> <blockquote> <p>.../line_items/update_quantity/id=28&amp;quantity=2&amp;cart=27</p> </blockquote> <p>without ?</p> <p>A have such routes:</p> <blockquote> <p>match 'line_items/:action/id=:id&amp;quantity=:quantity&amp;cart=:cart' =&gt; 'line_items#update_quantity'</p> </blockquote> <p>I tried, but nothing goes right. Help me please.</p> <pre><code>def update_quantity @cart = current_cart @line_item = LineItem.find(params[:id]) respond_to do |format| if @line_item.update_attribute(:quantity, params[:quantity]) #&amp;&amp; @cart.id == params[:cart] format.html { redirect_to(@line_item, :notice =&gt; 'Line item was successfully updated.') } format.js format.xml { head :ok } else format.html { render :action =&gt; "edit" } format.xml { render :xml =&gt; @line_item.errors, :status =&gt; :unprocessable_entity } end end end </code></pre> </div>

AJAX用于上/下投票

<div class="post-text" itemprop="text"> <p>I'm trying to implement upvote/downvote for forum posts. I have some Jquery code written up and it's working when you click the up-arrow or the down-arrow. But there are two issues:</p> <ol> <li><p>There is an up arrow like I mentioned that I'm using from bootstrap and then to the right of the arrows I have a counter for how many times each post was upvoted and downvoted. There is some default spacing, that I guess comes from bootstrap. When I click the button, the arrow and the corresponding counter number lose their spacing. But go back to normal when I refresh the page.</p></li> <li><p>When a user clicks the up arrow, the arrow and counter turn green. And when a user clicks the down arrow, the down arrow and counter turn red (only to the current user). When I refresh or go back to the page, the color disappears and goes back to normal. How can I get the colors of the voted posts to stay for the current user?</p></li> </ol> <p><strong>_forum_post.html.erb</strong></p> <pre><code>&lt;div class="pull-left vote-links"&gt; &lt;%= link_to like_forum_forum_thread_forum_post_path(@forum, @forum_thread, forum_post), class: 'glyphicon glyphicon-triangle-top upvoteButton', method: :put do %&gt; &lt;%= forum_post.get_upvotes.size %&gt; &lt;% end %&gt;&lt;br /&gt; &lt;%= link_to dislike_forum_forum_thread_forum_post_path(@forum, @forum_thread, forum_post), class: 'glyphicon glyphicon-triangle-bottom downvoteButton' , method: :put do %&gt; &lt;%= forum_post.get_downvotes.size %&gt; &lt;% end %&gt; &lt;/div&gt; </code></pre> <p><strong>forum_posts.js</strong></p> <pre><code>$(document).ready(function() { $('.vote-links').on('click', 'a', function(e) { e.preventDefault(); var currentTarget = $(e.currentTarget); var voteLinksDiv = currentTarget.parents('.vote-links'); if (currentTarget.is('.upvoteButton')) { currentTarget.css({color: 'green'}); voteLinksDiv.find('.downvoteButton').css({color: '#333'}); } else { currentTarget.css({color: 'red'}); voteLinksDiv.find('.upvoteButton').css({color: '#333'}); } $.ajax({ url: currentTarget.attr('href'), type: 'PUT', data: { format: 'json' }, dataType: 'json', complete: function(xhr, textStatus) { voteLinksDiv.find('a.upvoteButton').text(xhr.responseJSON.upvote); voteLinksDiv.find('a.downvoteButton').text(xhr.responseJSON.downvote); } }); return false; }); }); </code></pre> <p><strong>forum_posts_controller.rb</strong></p> <pre><code>def upvote @forum_post.upvote_by current_user respond_to do |format| format.html { redirect_to :back } format.json { render :json =&gt; { downvote: @forum_post.get_downvotes.size, upvote: @forum_post.get_upvotes.size } } format.js end end def downvote @forum_post.downvote_by current_user respond_to do |format| format.html { redirect_to :back } format.json { render :json =&gt; { downvote: @forum_post.get_downvotes.size, upvote: @forum_post.get_upvotes.size } } format.js end end </code></pre> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

一文带你入门Java Stream流,太强了

两个星期以前,就有读者强烈要求我写一篇 Java Stream 流的文章,我说市面上不是已经有很多了吗,结果你猜他怎么说:“就想看你写的啊!”你看你看,多么苍白的喜欢啊。那就“勉为其难”写一篇吧,嘻嘻。 单从“Stream”这个单词上来看,它似乎和 java.io 包下的 InputStream 和 OutputStream 有些关系。实际上呢,没毛关系。Java 8 新增的 Stream 是为...

立即提问
相关内容推荐