I'm relatively new to Ruby on Rails so please don't mind my newbie level!
I have following models:
class Paintingdescription < ActiveRecord::Base
belongs_to :paintings
belongs_to :languages
end
class Paintingtitle < ActiveRecord::Base
belongs_to :paintings
belongs_to :languages
end
class Painting < ActiveRecord::Base
has_many :paintingtitles, :dependent => :destroy
has_many :paintingdescriptions, :dependent => :destroy
has_many :languages, :through => :paintingdescriptions
has_many :languages, :through => :paintingtitles
end
class Language < ActiveRecord::Base
has_many :paintingtitles, :dependent => :nullify
has_many :paintingdescriptions, :dependent => :nullify
has_many :paintings, :through => :paintingtitles
has_many :paintings, :through => :paintingdescriptions
end
In my painting new/edit view, I would like to show the painting details, together with its title and description in each of the languages, so I can store the translation of those field.
In order to build the languagetitle and languagedescription records for my painting and each of the languages, I wrote following code in the new method of my Paintings_controller.rb:
#temp_languages = #languages
#languages.size.times{#painting.paintingtitles.build}
#painting.paintingtitles.each do |paintingtitle|
paintingtitle.language_id = #temp_languages[0].id
#temp_languages.slice!(0)
end
#temp_languages = #languages
#languages.size.times{#painting.paintingdescriptions.build}
#painting.paintingdescriptions.each do |paintingdescription|
paintingdescription.language_id = #temp_languages[0].id
#temp_languages.slice!(0)
end
In form partial which I call in the new/edit view, I have
<% form_for #painting, :html => { :multipart => true} do |f| %>
...
<% languages.each do |language| %>
<p>
<%= label language, language.name %>
<% paintingtitle = #painting.paintingtitles[counter] %>
<% new_or_existing = paintingtitle.new_record? ? 'new' : 'new' %>
<% prefix = "painting[#{new_or_existing}_title_attributes][]" %>
<% fields_for prefix, paintingtitle do |paintingtitle_form| %>
<%= paintingtitle_form.hidden_field :language_id%>
<%= f.label :title %><br />
<%= paintingtitle_form.text_field :title%>
<% end %>
<% paintingdescription = #painting.paintingdescriptions[counter] %>
<% new_or_existing = paintingdescription.new_record? ? 'new' : 'new' %>
<% prefix = "painting[#{new_or_existing}_title_attributes][]" %>
<% fields_for prefix, paintingdescription do |paintingdescription_form| %>
<%= paintingdescription_form.hidden_field :language_id%>
<%= f.label :description %><br />
<%= paintingdescription_form.text_field :description %>
<% end %>
</p>
<% counter += 1 %>
<% end %>
...
<% end %>
But, when running the code, ruby encounters a nil object when evaluating paintingdescription.new_record?:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.new_record?
However, if I change the order in which I
a) build the paintingtitles and painting descriptions in the paintings_controller new method and
b) show the paintingtitles and painting descriptions in the form partial
then I get the nil on the paintingtitles.new_record? call.
I always get the nil for the objects I build in second place. The ones I build first aren't nil in my view.
Is it possible that I cannot build objects for 2 different associations at the same time? Or am I missing something else?
Thanks in advance!
Actually I found a pretty simple solution. I provide a hash with values for the language ids when building the records.
#languages = Language.all
#languages.each do |language|
#painting.paintingtitles.build( {:language_id => language.id} )
#painting.paintingdescriptions.build( {:language_id => language.id} )
end
Related
So im working through the Odin Project's "Flight Booker" project. https://www.theodinproject.com/courses/ruby-on-rails/lessons/building-advanced-forms. Which essentially is what it sounds like and im running into a problem with passing nested attributes.
First and foremost the Relevant Models:
class Booking < ApplicationRecord
belongs_to :passenger
belongs_to :flight
accepts_nested_attributes_for :passenger
end
class Flight < ApplicationRecord
has_many :bookings, dependent: :destroy
has_many :passengers, through: :bookings
belongs_to :to_airport, class_name: 'Airport', foreign_key: 'origin_id'
belongs_to :from_airport, class_name: 'Airport', foreign_key: 'destination_id'
end
class Passenger < ApplicationRecord
has_many :bookings, dependent: :destroy
has_many :flights, through: :bookings
end
The passenger schema just contains an email and name for right now. But the problem is when I pass the information to the "booking" controller. Here is my "New" form for booking.
<%= form_for #booking do |f| %>
<%= f.hidden_field :flight_id, value: params[:booking][:flight_num] %>
<%= f.hidden_field :passengers_num, value: params[:booking][:passengers_num] %>
<% params[:booking][:passengers_num].to_i.times do |passenger| %>
<%= fields_for :passenger do |passenger| %>
<%= passenger.label :name, 'Name', class: "Label" %>
<%= passenger.text_field :name %>
<%= passenger.label :email, 'email', class: "Label" %>
<%= passenger.email_field :email %>
<% end %>
<% end %>
<%= f.submit "Book Flight" %>
<% end %>
(Ignore the hidden fields for now, they are passed from the "Flights" search page and Im getting those just fine.)
So I am getting the multiple forms (name and email fields) but when I "Submit" I am only getting parameters for the last field sets. (So if there are 3 sets of name/email fields, I only get parameters for the last one).
It's possible im not understanding the fields_for however as I can't find a ton of good examples.
Thanks!
There could be many issues with your implementation...I'll layout a few...
Move <% params[:booking][:passengers_num].to_i.times do |passenger| %> logic into the new action of your bookings controller...ie
def new
#booking = Booking.new
3.times { #booking.passengers.new } # or whatever your logic is to display x amount of passenger fields
end
Make sure that in your bookings controller you are permitting the nested attributes like this...
params.require(:booking).permit(passengers_attributes: [:name, :email])
As far as the form, you'll need to treat it like a form within a form (makes sense...nested attributes created from a nested form!) and use the block variable...like this
<ul>
<%= f.fields_for :passengers do |passenger_form| %>
<li>
<%= passenger_form.label :name
<%= passenger_form.text_field :name %>
</li>
<!-- other permitted fields -->
<% end %>
</ul>
I'm kinda new to ruby on rails, I've been reading documentation on assosiations and I've been having an easy time (and usually a quick google search solves most of my doubts) however recently I'm having problems with a seemingly easy thing to do.
What I'm trying to do is to create an Event, linked to an existing Category.
Event model
class Event < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
.
.
.
end
Category model
class Category < ApplicationRecord
has_many :categorizations
has_many :events, through: :categorizations
end
Categorization model
class Categorization < ApplicationRecord
belongs_to :event
belongs_to :category
end
Event controller
class EventsController < ApplicationController
def new
#event = Event.new
end
def create
#user = User.find(current_user.id)
#event = #user.events.create(event_params)
if #event.save
redirect_to root_path
else
redirect_to root_path
end
end
private
def event_params
params.require(:event).permit(:name, category_ids:[])
end
Here is the form, which is where I think the problem lies:
<%= form_for #event, :html => {:multipart => true} do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :categorizations do |categories_fields|%>
<% categories = [] %>
<% Category.all.each do |category| %>
<% categories << category.name %>
<% end %>
<%= categories_fields.label :category_id, "Category" %>
<%= categories_fields.select ( :category_id, categories) %>
<% end %>
.
.
.
<%= f.submit "Create"%>
<% end %>
I previously populate the Category db with some categories, so what's left to do is to while creating an event, also create a categorization that is linked both to the new event and the chosen Categorization. but the things I've tried don't seem to be working.
Other things seem to be working ok, whenever I try to submit the event all things are populated as expected except the categorization.
As you mentioned that you are new to rails, you'll find this cocoon gem very interesting. You can achieve what you wanted. And the code will cleaner.
I don't have the points to comment, that's why I am giving this as an answer.
I am making a model where users can belong to multiple teams and teams have multiple people.
I have checkboxes but they don't pass the value onto the object.
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :teams
accepts_nested_attributes_for :teams
end
class Team < ActiveRecord::Base
has_many :users
attr_accessible :name
end
Here is the code in my controller
def create
#users = User.all
#user = User.new
#teams = Team.all
#user.attributes = {:teams => []}.merge(params[:user] || {})
end
Here is the code in my view file
<%= form_for #user, url: {action: "create"} do |f| %>
<%= f.label :teams%>
<% for team in #teams %>
<%= check_box_tag team.name, team.name, false, :teams => team.name%>
<%= team.name -%>
<% end %>
<%= submit_tag "Create User" %>
I am trying to show it into
<%= user.teams.name %>
But the only output is "Team"
Can someone tell me what I am doing wrong?
Actually, you can't do a many-to-many relationship that way... you need to do has_many :through or alternatively has_and_belongs_to_many Nice explanation here...
http://guides.rubyonrails.org/association_basics.html
I am currently working on a nested model form.
I have a subject model.
This subject model has lessons of 3 different types - tutorial, lecture and laboratory.
I am able to get the nested form working with https://github.com/ryanb/nested_form.
But I want to fix it such that in the form only 3 forms for the child(lesson model) will be produced and that their first field (lesson_type field) will be automatically filled in and fixed.
I am not too sure on how to model such a situation on Rails.
These are the codes I have so far.
Any advice on what I could try out or point out the mistakes I have made would be appreciated.
This is the form.
Right now I could get the form to show up three times on my controller but I am not sure how I could generate different values for the fields. They are all showing lecture as of now.
<%= nested_form_for(#subject, :remote=>true) do |f| %>
<div class="field">
<%= f.label :subject_code %><br />
<%= f.text_field :subject_code %>
</div>
<%= f.fields_for :lessons do |lesson_form| %>
<%= lesson_form.label :lesson_type %><br/>
<%= lesson_form.text_field :lesson_type, :value=> "lecture"%><br/>
<%= lesson_form.label :name %><br/>
<%= lesson_form.text_field :name %><br/>
<%= lesson_form.fields_for :lesson_groups do |lesson_group_form| %>
<%= lesson_group_form.label :group_index %><br/>
<%= lesson_group_form.text_field :group_index %>
<%= lesson_group_form.link_to_remove "Remove this task" %>
<% end %>
<p><%= lesson_form.link_to_add "Add a lesson_group",:lesson_groups,:id=>"open-lesson"%></p>
<% end %>
<% end %>
This is the controller. The creation will happen on the index page.
def index
#subjects = Subject.all
#subject = Subject.new
lecture = #subject.lessons.build
lecture.lesson_groups.build
lecture.destroy
tutorial = #subject.lessons.build
tutorial.lesson_groups.build
tutorial.destroy
laboratory = #subject.lessons.build
laboratory.lesson_groups.build
laboratory.destroy
respond_to do |format|
format.html # index.html.erb
format.json { render json: #subjects }
format.js
end
end
The subject model
class Subject < ActiveRecord::Base
attr_accessible :subject_code, :lessons_attributes
has_many :lessons, :dependent => :destroy
accepts_nested_attributes_for :lessons, :allow_destroy => :true, :reject_if => lambda { |a| a[:lesson_type].blank? }
end
And the lesson model
class Lesson < ActiveRecord::Base
belongs_to :subject
attr_accessible :lesson_type, :name, :subject, :lesson_groups_attributes
has_many :lesson_groups, :dependent => :destroy
accepts_nested_attributes_for :lesson_groups, :allow_destroy => true
end
Okay, I am not sure if this is to the Rails convention but I got it working according to what I want. Added the following lines in the subject model: Basically assigning the lesson type field in the model.
lecture = #subject.lessons.build
lecture.lesson_type = "lecture"
lecture.lesson_groups.build
lecture.destroy
tutorial = #subject.lessons.build
tutorial.lesson_type = "tutorial"
tutorial.lesson_groups.build
tutorial.destroy
laboratory = #subject.lessons.build
laboratory.lesson_type = "laboratory"
laboratory.lesson_groups.build
laboratory.destroy
And to make it such that they can't change the lesson type I made it read only
<%= lesson_form.text_field :lesson_type, :readonly=>true%><br/>
I'm using Searchlogic to search on many fields in a database. One of those fields is a :has_may, :through => relationship, and I can't get it to work.
Here are the relevant parts of the models:
Source.rb:
class Source < ActiveRecord::Base
has_many :authorships
has_many :authors, :through => :authorships
end
Authorship.rb:
class Authorship < ActiveRecord::Base
belongs_to :source
belongs_to :author
end
Author.rb:
class Author < ActiveRecord::Base
has_many :authorships
has_many :sources, :through => :authorships
end
Then, in my view, I have:
<% form_for #search do |f| %>
<fieldset><legend>Search the Online Medieval Sources Bibliography</legend>
<% f.fields_for #search.conditions do |sources| %>
<%= sources.hidden_field :live_not_null %>
<p>
Text Name:
<%= sources.text_field :text_name_like, :size => 95 %> <br />
<% sources.fields_for :author do |authors| %>
Medieval Author:
<%= authors.text_field :name_like, :size => 90 %>
<% end %> <br />
Modern Editor/Translator:
<%= sources.text_field :editor_like, :size => 80 %> <br />
</p>
<% end %>
</fieldset>
<p>
<%= f.submit "Search" %>
</p>
<% end %>
The search page loads just fine, but hitting the "submit" button gives me the following error:
Searchlogic::Search::UnknownConditionError in SourcesController#index
The author is not a valid condition. You may only use conditions that map to a named scope
Here is the code from SourcesController:
class SourcesController < ApplicationController
def index
query = if params[:search] then
params[:search][:hash]
end
#search = Source.search(query)
#sources = #search.all
end
And here are the parameters:
Parameters: {"commit"=>"Search", "search"=>{"hash"=>{"text_name_like"=>"canterbury", "date_begin_greater_than_or_equal"=>"", "author"=>{"name_like"=>""}, "editor_like"=>"", "link_not_blank"=>"0", "trans_none_not_null"=>"0", "trans_other_not_null"=>"0", "trans_english_not_null"=>"0", "trans_french_not_null"=>"0", "region_like"=>"", "live_not_null"=>"", "app_facsimile_not_null"=>"0", "date_end_less_than_or_equal"=>""}, "order"=>""}}
Does anyone have any ideas about what is happening here? Do you need to see more of the error message?
Many thanks!
I too have come across this limitation on searchlogic. there is a 'hack' of a solution that i got. its simple really.
search for items you looking for on the join model. this will give you the ids of the models that have that search.
this is a bit quirky but its the closest solution i could offer you.
hope this helps.
:)