2015-04-22 86 views
1

我有一个索引视图,显示了所有可用的类,我想要一个链接到“注册类”,将我重定向到“注册”表单并填充一些其他值而注册在创建时可以节省我填补了再加上我只是通过链接传递给方法的类的外键的值在rails上通过link_to方法传递参数4

类指标:

<h1>Listof classes</h1> 

<table> 
    <thead> 
    <tr> 
     <th>id</th> 
     <th>Name</th> 
     <th>Description</th> 
     <th>Actions</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @classes.each do |class| %> 
     <tr> 
     <td><%= class.id %></td> 
     <td><%= class.name %></td> 
     <td><%= class.description %></td> 
     <td><%= link_to 'sign up!', new_sign_up_path(:class_id => class.id), method: :post %></td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 

sign_up控制器:

class SignUpsCOntroller < ApplicationController 
    before_action :set_sign_ups, only: [:show, :edit, :update, :destroy] 

    # GET /sign_ups/new 
    def new 
    @sign_up = SignUp.new 
    end 

    def set_sign_ups 
     @sign_up = SignUp.find(params[:id]) 
    end 

    def sign_up_params 
     params.require(:sign_up).permit(:date, :status, :type, :class_id) 
    end 
end 

和我的注册量形式:

<%= form_for(@sign_up) do |f| %> 

    <div class="field"> 
    <%= f.label :date %><br> 
    <%= f.date_select :date %> 
    </div> 
    <div class="field"> 
    <%= f.label :status %><br> 
    <%= f.check_box :status %> 
    </div> 
    <div class="field"> 
    <%= f.label :type %><br> 
    <%= f.number_field :type %> 
    </div> 
    <div class="field"> 
    <%= f.hidden_field :class_id %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

当我保存它,它不保存的...类标识码我已经试过解析成整型我已经试过了没有隐藏字段,但它通过它作为空白保存...任何想法?

+1

命名不是'class'其他变量的东西 - 那就是在Ruby中的保留字。 – deefour

+2

借调。如果你开始命名变量'class'和'type',你将会进入痛苦的世界。 – Shadwell

+0

他们实际上被称为不同,因为我的代码是西班牙语我改变它当我发布的东西 – fr3d0

回答

2

您刚刚通过params[:class_id],并在link_to上附加了您的额外参数。但是您的形式是一个class_id属性的对象,因此期待您的@sign_up对象有一个class_id属性。

基本上你new动作,您需要设置@sign_upclass_id它从参数:

def new 
    @sign_up = SignUp.new 
    @sign_up.class_id = params[:class_id] if params.has_key?(:class_id) 
end 

这将class_id设置为从link_to URL传入的参数。

然后您的表单应该可以正常工作,因为f.hidden_field将查看@sign_up上的当前值class_id并将其设置为输入的值。不要紧,你在这一点上还没有保存 - form_for将使用未保存的状态填充输入。

+0

我现在甚至不确定'@ daw_inscripcion'来自哪里。这个表单是否应该用于'@ sign_up'? – Shadwell

+0

是的是对不起,这只是我的代码是西班牙文我改变它,当我发布的东西对不起 – fr3d0

+0

德纳达(你不会比我更害怕西班牙语,我很害怕!) – Shadwell