开发者

Setting Symbols in Form View - Ruby on Rails

I am having problems trying to set symbol values in a form view. My view has a couple instance variables being used, @task and @team, @team is the one im having issues with. Tasks have a :team value that needs to be set. In this view @team holds a value, but when I hit the "Create" button and make a post, the @team value is lost, and @task contains no team value.

Here is the view I'm dealing with:

Note: the ":team => @task.team" line doesn't work

<% form_for(@task) do |f| %>
  <%= f.error_messages %>
  <% @task.team = Team.find(@team) %>
  <开发者_如何学编程p><%= @task.team.title%></p>
  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :hours %><br />
    <%= f.text_field :hours %>
  </p>

  <p>
    <%= f.label :team %><br />
    <% :team => @task.team %>
  </p>
  <p>
    <%= f.submit 'Create'%>
  </p>
<% end %>

The Post method that gets called on Create:

 def create
    @task = Task.new(params[:task])

    respond_to do |format|
      if @task.save
        format.html { redirect_to(@task, :notice => 'Task was successfully created.') }
        format.xml  { render :xml => @task, :status => :created, :location => @task }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end


@Jordinl is right when he mentions that you could use a hidden form field. You can also automatically scope the task to the team in the controller by doing something like

@team = Team.find(params[:team])

and then

@team.tasks << Task.new(params[:task])

You'll need to have a has_many association set up in the team model for tasks

has_many :tasks

for this to work. Each task will also need the team id as well but it sounds like you already have that.


Why don't you set it as a hidden field?

<%= f.hidden_field :team, :value => @task.team %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜